import {
  ChangeDetectorRef,
  Component,
  Input,
  OnInit,
  ViewChild
} from '@angular/core';
import { NzFormatEmitEvent, NzMessageService, NzModalRef } from 'ng-zorro-antd';
import { SFComponent, SFSchema, SFSchemaEnumType } from '@delon/form';
import { ApiService } from '@core/services/api';
import { _HttpClient } from '@delon/theme';
import { AreaService } from '../../../area-manage/area.service';
import { HttpClient } from '@angular/common/http';
import { UtilService } from '@core/services/util.service';

@Component({
  selector: `app-add-modal`,
  templateUrl: './add.component.html',
  styleUrls: ['./index.less']
})
export class AddComponent implements OnInit {
  @ViewChild('sf', { static: false }) sf: SFComponent;
  @Input() type: 0 | 1;
  @Input()
  set _param(value) {
    console.log(value);
    if (!value) return;
    this.flag=false;
    setTimeout(()=>{
      this.getAreaTreeNode(value.state).then((res)=>{
        let arr=res.map(item =>{
          return {label:item.title,value:item.key}
        })
        if(this.util.getStorage('userAccount') != '"admin"'){
          arr=arr.filter(item => item.value == this.city);
        }
        const statusProperty = this.sf.getProperty('/city')!;
        statusProperty.schema.enum=arr;
        statusProperty.widget.reset('');
      });
    },0)

    this.getTree(value.city).then((res)=>{
      let arr=this.transformTree(res);
      let list=[];
      let arr2=[];
      
      console.log(arr2);
      if(this.util.getStorage("userAccount") == '"admin"'){
        list=arr;
      }else{
        for(let item of this.cities){
          let arr3=this.sonsTree(arr,item.cityId,[]);
          arr2=[...arr2,...arr3];
        }
        list=arr2;
      }
      const statusProperty = this.sf.getProperty('/cityId')!;
      statusProperty.schema.enum=list;
      statusProperty.widget.reset('');
    });

    this.param = value;
    this.param.cityId = value.cities.map(item => item.cityId);
  };
  param: any;
  showForm = false;
  flag:boolean = true;
  city:any;
  province:any;
  cities:any;
  schema: SFSchema = {
    properties: {
      deptName: {
        type: 'string',
        title: '名称'
      },
      deptFullName: {
        type: 'string',
        title: '全称',
      },
      state: {
        type: 'string',
        title: '省',
        enum:[],
        ui:{
          widget: 'select',
          change: (value, orgData) => {
            this.getAreaTreeNode(value).then((res)=>{
              let arr=res.map(item =>{
                return {label:item.title,value:item.key}
              })
              if(this.util.getStorage('userAccount') != '"admin"'){
                arr=arr.filter(item => item.value == this.city);
              }
              const statusProperty = this.sf.getProperty('/city')!;
              statusProperty.schema.enum=arr;
              statusProperty.widget.reset('');
            });
          },
        }
      },
      city: {
        type: 'string',
        title: '市',
        enum:[],
        ui:{
          widget: 'select',
          change: (value, orgData) => {
            this.getTree(value).then((res)=>{
              console.log(res);
              let arr=this.transformTree(res);
              console.log(arr);
              let arr2=[];
              let list=[];
              if(this.util.getStorage("userAccount") == '"admin"'){
                list=arr;
              }else{
                for(let item of this.cities){
                  let arr3=this.sonsTree(arr,item.cityId,[]);
                  arr2=[...arr2,...arr3];
                }
                list=arr2;
              }
              const statusProperty = this.sf.getProperty('/cityId')!;
              statusProperty.schema.enum=list;
              statusProperty.widget.reset('');
            });
          },
        }
      },
      cityId: {
        type: 'string',
        title: '权限区域',
        enum: [],
        ui: {
          widget: 'tree-select',
          checkable: true,
          multiple: true,
          hideUnMatched:true,
          checkStrictly:true,
          dropdownStyle: {
            'max-height': '300px'
          }
        }
      },
      status: {
        type: 'string',
        title: '状态',
        enum: [
          {label: '启用', value: true},
          {label: '停用', value: false},
          ]
      },
      deptRemark: {
        type: 'string',
        title: '备注'
      }
    },
    required: ['deptName', 'cityId','state','city']
  }
  submit(data): void {
    const body = JSON.parse(JSON.stringify(data))
    body.cities = data.cityId.map(item => {
      return {cityId: item};
    })
    delete body.cityId;
    body.deptType = '1';
    const url = this.type === 0 ? this.api.permision.add.url : this.api.permision.update.url;
    const method = this.type === 0 ? this.api.permision.add.method : this.api.permision.update.method
    this.http.request<any>(method, url,  { body}).subscribe(res => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.triggerOk();
      } else {
        this.msg.error(res.message)
      }
    })
  }
  constructor(
    private api: ApiService,
    private ref: ChangeDetectorRef,
    private msg: NzMessageService,
    private http: HttpClient,
    private modalRef: NzModalRef,
    private area: AreaService,
    private util: UtilService,
  ) { }

  ngOnInit() {
    //440304
    this.getAreaTreeNode(0).then(res => {
      console.log(res);
      let arr=res.map(item =>{
        return {label:item.title,value:item.key}
      })
      console.log(this.util.getStorage('userAccount'))
      if(this.util.getStorage('userAccount') != '"admin"'){
        arr=arr.filter(item => item.value == this.province);
      }
      this.schema.properties.state.enum = arr;
      this.ref.detectChanges();
      this.showForm=true;
    })
    this.getDepts();
  }
  //获取当前用户的权限范围
  getDepts(){
    const depts=JSON.parse(this.util.getStorage("depts"));
    this.city=depts.city;//市
    this.province=depts.state;//省
    this.cities=depts.cities;//区，街道，小区
    console.log(depts);
  }
//  treeExpandChange(event:NzFormatEmitEvent): void {
//     // load child async
//     if (event.eventName === 'expand') {
//       const node = event.node;
//       if (node && node.getChildren().length === 0 && node.isExpanded) {
//         console.log(event)
//         this.loadNode(event.node).then(data => {
//           if(node.level == 5) {
//             data.forEach( item => {
//               item.isLeaf = true;
//             })
//           }
//           node.addChildren(data);
//         }, () => {
//           node.addChildren([])
//         });
//       }
//     }
//   }
//   loadNode(data): Promise <any>{
//     return this.getAreaTreeNode(data.key)
//   }
//获取省，市
  getAreaTreeNode(id): Promise<any> {
    return new Promise<any>((resolve, reject) => {
      this.http.post(this.api.city.tree.url, {id}).subscribe((res:any) => {
        console.log(res);
        if (res.data && res.data.length > 0) {
          const node = res.data.map(item => {
            return {
              key: item.id,
              title: item.name,
              level: item.cityRank,
              rank: Number(item.rank),
              parentAllId: item.parentAllId,
              parentId:item.parentId
            }
          })
          resolve(node);

        } else {
          resolve([])
        }
      })
    })
  }
//获取市下面的区，街道，小区
  getTree(id):Promise<any>{
    return new Promise<any>((resolve, reject) => {
      this.http.post(this.api.city.allTree.url, {id}).subscribe((res:any) => {
        if (res.data && res.data.length > 0) {
          let node = res.data.map(item => {
            return {
              key: item.id,
              title: item.name,
              rank: Number(item.rank),
              // parentAllId: item.parentAllId,
              // parentId:item.parentId,
              pId:item.parentId,
              id:item.id
            }
          })
          node=node.filter(item => item.rank < 9);
          resolve(node);
        } else {
          resolve([])
        }
      })
    })
  }

//找到某一父节点下的所有子节点
  sonsTree(arr, id,temp) {
   for(let item of arr){
     if(item.id == id){
       temp.push(item);
     }else{
       if(item.children && item.children.length > 0){
          this.sonsTree(item.children,id,temp);
       }
     }
   }
    return temp;
  }

  //扁平化数据转树形结构
 transformTree (list) {
    const tree = []
    
    for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].pId && list[i].rank == 3) {
            const item = this.queryChildren(list[i], list)
            
            tree.push(item)
        }
    }
    
    return tree
}

queryChildren (parent, list) {
    const children = []
    
    for (let i = 0, len = list.length; i < len; i++) {
        if (list[i].pId === parent.id) {
            const item = this.queryChildren(list[i], list)

            children.push(item)
        }
    }
    
    if (children.length) {
        parent.children = children
    }
    
    return parent
}

  searchData(e) {
    console.log(e);
    // 发送请求，将新增或修改后的数据提交上去
  }
}
